import api from '@/api';
import { AppConfig } from '@jl/common/src/api/user.typing';
import { getAppConfig, updateAppConfig } from '@jl/common/src/api/user';
import { defineStore } from 'pinia';
import { getLicensedFirstCompany } from '@/api/project';
import { getAbsolutePath } from '@jl/common/utils';

function changeFavicon(newIconPath: string) {
  // 创建一个新的 link 元素
  var link = document.createElement('link');

  // 设置 link 元素的属性
  link.type = 'image/png';
  link.rel = 'icon';
  link.href = newIconPath;

  // 获取当前文档的 head 元素
  var head = document.head || document.getElementsByTagName('head')[0];

  // 移除之前的图标（可选）
  var existingFavicon = document.querySelector('link[rel="icon"]');
  if (existingFavicon) {
    head.removeChild(existingFavicon);
  }

  // 将新的 link 元素添加到 head 中
  head.appendChild(link);
}

export const useGlobalStore = defineStore('global', () => {
  const defaultSrc = getAbsolutePath('images/logo.png');
  const defaultFavicon = getAbsolutePath('/favicon.ico');
  const appConfig = ref<AppConfig>();
  const companyInfo = ref<any>({});
  const logo = computed(() => {
    const path =
      getDetailField().favicon === defaultFavicon
        ? defaultFavicon
        : '/attachment' + getDetailField().favicon;
    changeFavicon(path);
    return getDetailField().logo === defaultSrc
      ? defaultSrc
      : '/attachment' + getDetailField().logo;
  });

  const getDetailField = (): any => {
    let detailField = {};
    try {
      detailField = JSON.parse(appConfig.value?.detailField ?? '{}');
    } catch (error) {}
    return detailField;
  };

  const getAppBaseConfig = async (appId: string, force = false): Promise<AppConfig> => {
    if (appConfig.value && !force) return appConfig.value;
    if (!appId) {
      return {} as AppConfig;
    }
    const data = await getAppConfig({ appId });
    appConfig.value = data;
    return data;
  };

  const updateAppBaseConfig = async (appBaseConfig: AppConfig): Promise<any> => {
    await updateAppConfig(appBaseConfig);
    getAppBaseConfig(appBaseConfig.appId, true);
  };

  const getCompany = async (): Promise<any> => {
    if (Object.keys(companyInfo.value).length) return companyInfo.value;
    const data = await getLicensedFirstCompany();
    companyInfo.value = data;
    return data;
  };

  return {
    defaultSrc,
    defaultFavicon,
    logo,
    appConfig,
    getAppBaseConfig,
    updateAppBaseConfig,
    getCompany,
  };
});
